package compiler

import (
	"context"
	"fmt"

	"github.com/go-playground/validator/v10"
	"gitverse.ru/dlc/similarity-compiler/internal/dto/service"
	"gitverse.ru/dlc/similarity-compiler/pkg/api/grpc/proto"
	"gitverse.ru/dlc/similarity-compiler/pkg/errors"
)

type compilerService interface {
	Compile(context.Context, service.CompileScriptInput) (*service.CompileScriptOutput, errors.Error)
}

type Deps struct {
	CompilerService compilerService `validate:"required"`
}

type Controller struct {
	compilerService compilerService
}

func New(deps Deps) (*Controller, errors.Error) {
	if err := validator.New().Struct(deps); err != nil {
		return nil, errors.NewWithError(
			fmt.Errorf("validate deps: %w", err),
			errors.ErrInternalError,
		)
	}

	return &Controller{
		compilerService: deps.CompilerService,
	}, nil
}

func (c *Controller) Compile(ctx context.Context, in *proto.CompileRequest) (*proto.CompileResponse, error) {
	compileScriptOutput, err := c.compilerService.Compile(ctx, service.CompileScriptInput{
		Language: in.GetLang(),
		Code:     in.GetCode(),
	})
	if err != nil {
		return nil, errors.GRPC(err)
	}

	return &proto.CompileResponse{
		Code: compileScriptOutput.Code,
	}, nil
}
